// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
}); // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext();
	let db = cloud.database();
	let cmd = db.command;
	let moreControls = {
		getCate: async () => {
			let data = await db.collection("swiperList").get();
			return data;
		}, //查看个人id
		getUserInfo() {
			// let data = await db.collection("user").where({
			// 	openid: wxContext.OPENID
			// })
			// return data
			return {
				event,
				openid: wxContext.OPENID,
				appid: wxContext.APPID,
				unionid: wxContext.UNIONID,
			};
		},
		// 注册
		async regist() {
			let {
				nickname,
				password,
				account,
				avater,
				auth
			} = event;
			let res = await db.collection("user").add({
				data: {
					nickname,
					password,
					openid: wxContext.OPENID,
					account: String(account),
					avater,
					auth: String(auth),
					bond: "0",
					phone: String(account),
				},
			});
			return res;
		},
		//查看是否注册
		async isregist() {
			let data = [];
			try {
				data = await db
					.collection("user")
					.where({
						openid: wxContext.OPENID,
					})
					.get();
				if (data?.data.length) {
					return {
						isregist: true,
						openid: wxContext.OPENID,
						data,
					};
				} else {
					return {
						isregist: false,
						openid: wxContext.OPENID,
						data,
					};
				}
			} catch (e) {
				return {
					isregist: false,
					openid: wxContext.OPENID,
					data,
				};
			}
		},
		// 发布走失并创建评论区
		async belost() {
			delete event.useName;
			let info = await db
				.collection("user")
				.where({
					// openid: event.openid
					openid: wxContext.OPENID,
				})
				.get();
			let res = await db.collection("lostpet").add({
				data: {
					...event,
					isfound: 0,
					count: moreControls.generateRandomNumber(50, 200),
					visitor: [], // 访问者
					session: [{
						username: info.data[0].nickname,
						avater: info.data[0].avater,
						// openid: event.openid,
						openid: wxContext.OPENID,
						talk: `大家如果有我家${event.pettype}线索评论给我，万分感谢！`,
						date: event.uploadDate,
					}, ],
					// openid: event.openid
					openid: wxContext.OPENID,
				},
			});
			return res;
		},
		// 查询走失宠物（本地服务）
		async getLostPet() {
			let res = null;
			let count = await db
				.collection("lostpet")
				.where({
					isfound: 0,
				}).count()
			if (event.limit) {
				// 倒序排列
				res = await db
					.collection("lostpet")
					.orderBy("uploadDate", "desc")
					.where({
						isfound: 0,
					})
					.limit(Number(event.limit))
					.get();

			} else {
				res = await db
					.collection("lostpet")
					.orderBy("uploadDate", "desc")
					.where({
						isfound: 0,
					})
					.limit(20)
					.get();
			}
			return {
				data: res.data,
				count: count.total
			}
		},
		// 向走失评论区发表评论
		async postSession() {
			let info = await db
				.collection("user")
				.where({
					openid: wxContext.OPENID,
					// openid: event.openid
				})
				.get();
			// update 函数第一个参数是data数据、data对象下是要更新的字段名使用cmd命令进行操作数组
			let res = await db
				.collection("lostpet")
				.doc(event.id)
				.update({
					data: {
						session: cmd.push({
							each: [{
								username: info.data[0].nickname,
								avater: info.data[0].avater,
								openid: wxContext.OPENID,
								talk: event.talk,
								date: event.date,
							}, ],
						}),
					},
				});
			return res;
		},
		// 获取宠物详情
		async getPetDetail() {
			let res = await db.collection("lostpet").doc(event.id).get();
			if (res.data.openid !== wxContext.OPENID && res.data.visitor.indexOf(wxContext.OPENID) == -1) {
				await moreControls.goodsCount("lostpet")
			}
			return res.data;
		},
		// 查看我的聊天会话
		async getSessionList() {
			let res = await db
				.collection("sessions")
				.where({
					"user.openid": wxContext.OPENID,
				})
				.orderBy("date", "desc")
				.get();
			return res;
		},
		// 创建会话 并且 创建消息表 自动发一条消息 你好我是XXX
		async createSession() {
			let res = await db.collection("sessions").add({
				data: {
					lastmessage: "",
					user: event.user,
					date: event.date,
				},
			});
			return res;
		},
		// 查询聊天详情
		async getSessionDetail() {
			let res = await db
				.collection("messages")
				.where({
					session_id: event.id,
				})
				.get();
			return res.data[0];
		},
		// 发送消息
		async sendMsg() {
			// 所需参数 ：会话id 头像地址 发送内容
			let res = await db
				.collection("messages")
				.where({
					session_id: event.id,
				})
				.update({
					data: {
						content: cmd.push({
							each: [{
								...event.content,
								sender: wxContext.OPENID, // 发送者
							}, ],
						}),
					},
				});
			return res;
		},
		// 创建消息
		async createMsg() {
			let res = await db.collection("messages").add({
				data: {
					content: [{
						...event.content,
						sender: wxContext.OPENID, // 发送者
					}, ],
					sender: wxContext.OPENID,
					receiver: event.receiver,
					session_id: event.sessionid,
				},
			});
			return res;
		},
		// 捡到、找到宠物
		async found() {
			delete event.useName;
			delete event.userInfo;
			let info = await db
				.collection("user")
				.where({
					// openid: event.openid
					openid: wxContext.OPENID,
				})
				.get();
			let res = await db.collection("found").add({
				data: {
					...event,
					isHave: 1,
					count: moreControls.generateRandomNumber(50, 200),
					visitor: [], // 访问者
					session: [{
						username: info.data[0].nickname,
						avater: info.data[0].avater,
						// openid: event.openid,
						openid: wxContext.OPENID,
						talk: `大家如果想要${event.type}请给我评论或直接电话联系！`,
						date: event.uploadDate,
					}, ],
					// openid: event.openid
					openid: wxContext.OPENID,
				},
			});
			return res;
		},
		// 查询捡到的宠物
		async searchLost() {
			let res = null;
			let count = await db
				.collection("found")
				.where({
					isHave: 1,
				}).count()
			if (event.limit) {
				// 倒序排列
				res = await db
					.collection("found")
					.orderBy("uploadDate", "asc")
					.where({
						isHave: 1,
					})
					.limit(Number(event.limit))
					.get();

			} else {
				res = await db
					.collection("found")
					.orderBy("uploadDate", "asc")
					.where({
						isHave: 1,
					})
					.limit(20)
					.get();
			}
			return {
				data: res.data,
				count: count.total
			}
		},
		// 新增宠物
		async addPet() {
			delete event.useName;
			delete event.userInfo;
			let info = await db
				.collection("user")
				.where({
					// openid: event.openid
					openid: wxContext.OPENID,
				})
				.get();
			let res = await db.collection("goodspet").add({
				data: {
					...event,
					isHave: 1,
					count: moreControls.generateRandomNumber(50, 200),
					visitor: [], // 访问者
					session: [{
						username: info.data[0].nickname,
						avater: info.data[0].avater,
						// openid: event.openid,
						openid: wxContext.OPENID,
						talk: `大家如果想要${event.race}请给我评论或直接电话联系！`,
						date: event.uploadDate,
					}, ],
					// openid: event.openid
					openid: wxContext.OPENID,
				},
			});
			return res;
		},
		// 查询宠物列表
		async getPetGoods() {
			let res = null;
			let count = await db
				.collection("goodspet")
				.where({
					isHave: 1,
				}).count()
			if (event.limit) {
				// 倒序排列
				res = await db
					.collection("goodspet")
					.orderBy("uploadDate", "asc")
					.where({
						isHave: 1,
					})
					.limit(Number(event.limit))
					.get();

			} else {
				res = await db
					.collection("goodspet")
					.orderBy("uploadDate", "asc")
					.where({
						isHave: 1,
					})
					.limit(20)
					.get();
			}
			return {
				data: res.data,
				count: count.total
			}
		},
		// 查询售卖宠物详情
		async searchPet() {
			let res = await db.collection("goodspet").doc(event.id).get();
			if (res.data.openid !== wxContext.OPENID && res.data.visitor.indexOf(wxContext.OPENID) == -1) {
				await moreControls.goodsCount("goodspet")
			}
			return res.data;
		},
		// 查询领养宠物详情
		async searchFound() {
			let res = await db.collection("found").doc(event.id).get();
			if (res.data.openid !== wxContext.OPENID && res.data.visitor.indexOf(wxContext.OPENID) == -1) {
				await moreControls.goodsCount("found")
			}
			return res.data;
		},
		// 向领养评论区发评论
		async postSessionToFound() {
			let info = await db
				.collection("user")
				.where({
					openid: wxContext.OPENID,
					// openid: event.openid
				})
				.get();
			// update 函数第一个参数是data数据、data对象下是要更新的字段名使用cmd命令进行操作数组
			let res = await db
				.collection("found")
				.doc(event.id)
				.update({
					data: {
						session: cmd.push({
							each: [{
								username: info.data[0].nickname,
								avater: info.data[0].avater,
								openid: wxContext.OPENID,
								talk: event.talk,
								date: event.date,
							}, ],
						}),
					},
				});
			return res;
		},
		// 向购买评论区发评论
		async postSessionToSale() {
			let info = await db
				.collection("user")
				.where({
					openid: wxContext.OPENID,
					// openid: event.openid
				})
				.get();
			// update 函数第一个参数是data数据、data对象下是要更新的字段名使用cmd命令进行操作数组
			let res = await db
				.collection("goodspet")
				.doc(event.id)
				.update({
					data: {
						session: cmd.push({
							each: [{
								username: info.data[0].nickname,
								avater: info.data[0].avater,
								openid: wxContext.OPENID,
								talk: event.talk,
								date: event.date,
							}, ],
						}),
					},
				});
			return res;
		},
		// 新增商品
		async addGoods() {
			delete event.useName;
			delete event.userInfo;
			let info = await db
				.collection("user")
				.where({
					// openid: event.openid
					openid: wxContext.OPENID,
				})
				.get();
			let res = await db.collection("goods").add({
				data: {
					...event,
					isHave: 1,
					count: moreControls.generateRandomNumber(50, 200),
					visitor: [], // 访问者
					session: [{
						username: info.data[0].nickname,
						avater: info.data[0].avater,
						// openid: event.openid,
						openid: wxContext.OPENID,
						talk: `欢迎大家选购本商品！`,
						date: event.uploadDate,
					}, ],
					// openid: event.openid
					openid: wxContext.OPENID,
				},
			});
			return res;
		},
		// 查询商品列表
		async getGoods() {
			let res = null;
			let count = await db
				.collection("goods")
				.where({
					isHave: 1,
				}).count()
			if (event.limit) {
				// 倒序排列
				res = await db
					.collection("goods")
					.orderBy("uploadDate", "asc")
					.where({
						isHave: 1,
					})
					.limit(Number(event.limit))
					.get();

			} else {
				res = await db
					.collection("goods")
					.orderBy("uploadDate", "asc")
					.where({
						isHave: 1,
					})
					.limit(20)
					.get();
			}
			return {
				data: res.data,
				count: count.total
			}
		},
		// 查询商品详情
		async searchGoods() {
			let res = await db.collection("goods").doc(event.id).get();
			if (res.data.openid !== wxContext.OPENID && res.data.visitor.indexOf(wxContext.OPENID) == -1) {
				await moreControls.goodsCount("goods")
			}
			return res.data
		},
		/**
		 * @param {string} page
		 * 实现商品访问量
		 */
		async goodsCount(page) {
			let goods = await db.collection(page).doc(event.id).update({
				data: {
					count: cmd.inc(1),
					visitor: cmd.push({
						each: [wxContext.OPENID]
					})
				}
			})
			return goods
		},
		// 生成随机数
		generateRandomNumber(min, max) {
			return Math.floor(Math.random() * (max - min + 1)) + min;
		}
	};
	return moreControls[event.useName]();
};